import general.Bid;
import general.ProductPrice;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.RemoteObject;
import java.util.UUID;
import java.util.Vector;

public class VickreyAuctioneer extends Auctioneer {
	private Vector<Bid> fBids;

	public static void main(String[] args) throws IOException {
		new VickreyAuctioneer();
	}

	public VickreyAuctioneer() throws IOException {
		super();
		fBids = null;
	}

	protected void newAuction() {
		fStatus = -1;
		fRunning = null;
		fBidders = new Vector<RemoteObject>();
		fWinner = null;
		fBids = new Vector<Bid>();
	}

	protected ProductPrice selectWinner() {
		Bid bWin = null;
		ProductPrice price = null;

		for (Bid b : fBids) {
			if (bWin == null) {
				bWin = b;
			}

			if (b.isLarger(bWin)) {
				price = bWin.getProductPrice();
				bWin = b;
			}
		}

		if (bWin != null) {
			fWinner = bWin.getBidder();
			fBidders.remove(fWinner);
		}
		return price;
	}

	public void placeBid(Bid b) {
		if (fRunning != null && fRunning.isRunning()) {
			fBids.add(b);
		}
	}

	public void joinAuction(RemoteObject c, String name, UUID id) throws RemoteException {
		if (fRunning != null && fRunning.isRunning()) {
			if (fReq.getProductID() == id) {
				fBidders.add(c);
			} else {
				// Bidding on wrong product
				throw new RemoteException("Join Error: joining auction for wrong product");
			}
		} else {
			throw new RemoteException("Join Error: No Auction Running");
		}
	}

	protected void cleanUp() {
		fBids = null;
		fRunning = null;
		fReq = null;
	}

	protected void updateBidders() {
		// Not allowed to update any bidders
	}

	public String getType() {
		return "Vickrey Auction";
	}
}
